package com.example.myapplication.kotlin

fun main() {
    //map
    val m2 = mutableMapOf(
        "pig" to "小猪",
        "cat" to "小猫",
        "dog" to "小狗",
        "chicken" to "小鸡"
    )

    println(m2["cat"])
    //添加
    m2["篮球"] = "篮球"
    println(m2["篮球"])
    //删除
    m2.remove("cat")
    println(m2["cat"])

    // 不可变 map
    val m1 = mapOf(
        "breakfast" to "早餐",
        "lunch" to "午餐",
        "dinner" to "晚餐"
    )
    m1.forEach({ key, value -> println("${key}:${value}") })
    // let
    var name = "小王"
    //当值存在的时候才会执行
    name?.let {
        println("$it,欢迎来到Kotlin")
    }
    // with
    class car {
        var name = "自行车"
        var price = 1200
        fun print() {
            println("$name:$price")
        }
    }
    //绑定了car的上下文对象，可以直接访问car的属性和方法
    with(car()) {
        println("$name,$price")
        print()
    }

    //run 可以创建一个临时工作区，可以执行多个操作，最后返回一个结果
    val result = run {
        val with = 120
        val hight = 100
        with * hight//返回结果
    }
    println(result)

    //apply 函数：作用域内计算 1 拿到一个新对象 2 在它的"身体"里做各种设置 3 最后自动返回配置好的对象
    // 创建一个手机对象
    class Phone {
        var owner = ""
        var wallpaper = "默认壁纸"
        var ringtone = "默认铃声"
        var apps = mutableListOf<String>()

        fun showSettings() {
            println("\n手机设置:")
            println("主人: $owner")
            println("壁纸: $wallpaper")
            println("铃声: $ringtone")
            println("安装的应用: ${apps.joinToString()}")
        }
    }
    //直接实例化
    val myPhone = Phone().apply {
        owner = "小王"
        wallpaper = "小王壁纸"
        ringtone = "小王铃声"
        apps.add("微信")
    }
    //showSettings 作用是显示手机的设置
    myPhone.showSettings()
    val momsPhone = Phone().apply {
        owner = "小王妈妈"
        wallpaper = "小王妈妈壁纸"
        ringtone = "小王妈妈铃声"
        apps.add("微信")
    }
    momsPhone.showSettings()
    //泛型
    fun <T> run(t: T): T {
        println("${t}在跑")
        return t
    }

    val how = run("小王")
    println(how)

    class food<T>(val name: T) {
        fun eat() {
            println("吃$name")
        }
    }

    val food = food<String>("小王")
    food.eat()
}